export function getDeviceUUID() {
  let deviceId = uni.getStorageSync('uni_deviceId') ||
    uni.getSystemInfoSync().deviceId ||
    uni.getSystemInfoSync().system + '_' + Math.random().toString(36).substr(2);

  uni.setStorageSync('uni_deviceId', deviceId)
  return deviceId;
}

export function friendlyDate(timestamp) {
  var formats = {
    'year': '%n% 年前',
    'month': '%n% 月前',
    'day': '%n% 天前',
    'hour': '%n% 小时前',
    'minute': '%n% 分钟前',
    'second': '%n% 秒前',
  };

  var now = Date.now();
  var seconds = Math.floor((now - timestamp) / 1000);
  var minutes = Math.floor(seconds / 60);
  var hours = Math.floor(minutes / 60);
  var days = Math.floor(hours / 24);
  var months = Math.floor(days / 30);
  var years = Math.floor(months / 12);

  var diffType = '';
  var diffValue = 0;
  if (years > 0) {
    diffType = 'year';
    diffValue = years;
  } else {
    if (months > 0) {
      diffType = 'month';
      diffValue = months;
    } else {
      if (days > 0) {
        diffType = 'day';
        diffValue = days;
      } else {
        if (hours > 0) {
          diffType = 'hour';
          diffValue = hours;
        } else {
          if (minutes > 0) {
            diffType = 'minute';
            diffValue = minutes;
          } else {
            diffType = 'second';
            diffValue = seconds === 0 ? (seconds = 1) : seconds;
          }
        }
      }
    }
  }
  return formats[diffType].replace('%n%', diffValue);
}

export function getQueryString(name, search = window.location.search || window.location.href) {
  const reg = new RegExp(`(^|&)?\\b${name}=([^&]*)(&|$)`)
  const r = reg.exec(search.substr(1))
  if (r != null) return unescape(r[2])
  return ''
}